package cn.ztydata.teachingsystem.heaven.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

/**
 * 数据访问基类
 * @author fanruiping
 * @since 2014-11-13
 */
public abstract class BaseDao {
    protected final Logger log = LoggerFactory.getLogger(BaseDao.class); //日志记录器

    @Autowired
    protected NamedParameterJdbcTemplate namedParameterJdbcTemplate; //jdbc模版类

    /**
     * 插入并返回主键
     * @param sql sql语句
     * @param parameters 参数
     * @return int
     *
     * @author fanruiping
     * @since 2014-11-13
     */
    protected long insertAndGetPrimaryKey(final String sql, MapSqlParameterSource parameters){
        KeyHolder keyHolder = new GeneratedKeyHolder();

        namedParameterJdbcTemplate.update(sql, parameters, keyHolder);

        return keyHolder.getKey().longValue();
    }

    /**
     * 获取mysql分页语句
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @return String 分页语句
     *
     * @author cx
     * @since 2014-07-11
     */
    protected String getLimitStr(final int pageNum, final int pageSize) {
        StringBuilder limit = new StringBuilder(" LIMIT ");
        limit.append((pageNum - 1) * pageSize).append(",").append(pageSize);

        return limit.toString();
    }
}
